Skip to content

🐞 MLXVLM: Fix Qwen3VL attention masks after cache rotation - #706

Merged
davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/fix-qwen3vl-rotating-cache-mask
Oct 23, 2026
Merged

davidkoski merged 1 commit into
ml-explore:mainfrom
aleroot:alessio/fix-qwen3vl-rotating-cache-mask

Conversation

@aleroot

@aleroot aleroot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Proposed changes

A Qwen3VL chat could generate normally, then crash when the next prompt arrived after its rotating KV cache had filled. Older keys had been evicted, but the absolute token offset kept growing, as required for rotary positions.

The original model port also used that offset to size the attention mask. This assumed every processed token was still cached. Once eviction began, the mask could describe more keys than the cache retained, causing SDPA to reject the shapes. Single-token decoding skipped this explicit mask, and previous continuation tests used unbounded caches, so the assumption went undetected.

This change builds the mask from the cache’s retained window and shares it across layers, while preserving absolute M-RoPE positions and the symbolic causal fast path.

The regression reproduced the crash before the fix.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure:

Build one shared attention mask from the retained cache window. Preserve absolute M-RoPE positions and add regressions for rotated, windowed, and image continuation.

@davidkoski davidkoski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change looks good, thank you!

It looks like Qwen3VLMoE has the same bug.

@davidkoski
davidkoski merged commit 0ea4465 into ml-explore:main Oct 23, 2026
4 checks passed
@aleroot

aleroot commented Oct 24, 2026

Copy link
Copy Markdown
Contributor Author

Change looks good, thank you!

It looks like Qwen3VLMoE has the same bug.

You are right. Fixed this and similar others in #728

wballard added a commit to swissarmyhammer/mlx-swift-lm-old that referenced this pull request Oct 24, 2026
Apply the upstream commits d02948b..991266a as a 3-way patch. CLAUDE.md is
excluded.

- 649f431 update for new TF32 comparison issues (ml-explore#721)
- 5ae2635 switch to MLXLogger (ml-explore#702)
- 260ada0 add ScriptedLogitsModel (ml-explore#719)
- 0ea4465 MLXVLM: Fix Qwen3VL attention masks after cache rotation (ml-explore#706)
- db2e7bf Expose request-scoped generation observations in ChatSession (ml-explore#714)
- 991266a Clear the MLX buffer cache after each prefill chunk (ml-explore#710)

Conflicts:
- Package.swift: both sides add the same README exclude; kept ours.
- ChatSession.swift: took upstream's transformer-based startGeneration and
  dropped the GenerationRun struct. Kept the fork's ReasoningHistory and
  thinkingEnabled capture. startGeneration takes an optional
  promptTokenCount, so the default path still counts the leading and
  checkpoint prefill tokens.

No new hybrid or recurrent models, so the post-merge ArraysCache.advance
checks do not apply.

Tests: MLXLMTests 894 XCTest and 1753 Swift Testing tests pass.
MLXGuidedGenerationTests 70, MLXFoundationModelsTests 374, CXGrammarTests 7,
MLXHuggingFaceMacrosTests 5 pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
davidkoski pushed a commit that referenced this pull request Oct 28, 2026
* 🐞 Fix attention masks sized from the absolute cache offset

A capacity-limited cache evicts keys while the absolute offset keeps
growing, so a mask sized from that offset describes more keys than the
cache presents and attention rejects the shapes. Qwen3VL fixed its own
case in #706. createAttentionMask(h:cache:) still built the array from
the raw offset, and Qwen3VLMoE used that and then sliced it again.

Both cache-list overloads now delegate to the cache makeMask, and
Qwen3VLMoE builds one shared mask from the retained window, as #706
does. M-RoPE positions stay absolute. Qwen3.5-VL no longer slices its
mask to an offset-derived length. That slice ended past the mask and
MLX clamps it, so the results do not change. The Qwen3 embedder folds
key padding across the same retained width.

Regressions cover warm continuation after rotation for Qwen3VLMoE and
Qwen3.5-VL, the padding fold, and the mask width of the shared helper.

* Gemma2: suppress boolean attention masks like mlx-lm

Gemma2 attention added its mask to the scores unconditionally, so a
boolean mask boosted the kept scores instead of hiding the masked keys
and multi-token prefill never matched token-by-token decode. Route it
through applyAttentionMask (bool masks suppress, float masks add),
matching mlx-lm gemma2.py, and expose that helper to model code.

* Gemma2: build the attention mask from the first layer cache
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants